<?php
namespace app\common\logic;

use app\common\model\Leibie;
use app\common\model\Order;
use Carbon\Carbon;
use think\Db;

class Tongji
{
    private $order='';

    public function __construct()
    {
        if(empty($this->order)){
            $this->order = new Order();
        }
    }

    public function selectAll($map=[],$fields='*'){
        return $this->order->where($map)->field($fields)->select();
    }

    /** 统计预产期
     * @return mixed
     */
    public function tongjiycq($map,$months){
        $leibie = new Leibie();
        $data = collect(Db::name('order')->where($map)->field('id,yiyuan,yctime')->select());
        $info['count'] = $data->count();
        $yiyuanInfo = $leibie->getYiyuan();
        foreach ($yiyuanInfo as $val){
            $info['detail'][$val['id']]['yiyuan_name'] = $val['name'];
            foreach ($months as $k=>$v){
                $info['detail'][$val['id']]['num'][$k] = $data->where('yiyuan',$val['id'])->where('yctime','>=',$v['start'])->where('yctime','<=',$v['end'])->count();
            }
        }
        return $info;
    }

    public function getTime($times=''){
        if(empty($times['ycstart']) && empty($times['ycend']) ){
            $yctime = [
                date('Y-m',strtotime('-2 months')),
                date('Y-m',strtotime('+2 months')),
            ];
        }elseif(empty($times['ycstart'])){
            $yctime = [
                date('Y-m',strtotime('-4 months',strtotime($times['ycend']))),
                $times['ycend'],
            ];
        }elseif(empty($times['ycend'])){
            $yctime = [
                $times['ycstart'],
                date('Y-m',strtotime('+4 months',strtotime($times['ycstart']))),
            ];
        }else{
            $yctime = [
                $times['ycstart'],
                $times['ycend'],
            ];
        }
        $monarr = array();
        $time = strtotime($yctime[0]);
        $time1 = Carbon::parse($yctime[0]);
        $monarr[] = [
            'month'=>date('n',$time).'月',// 当前月;
            'start'=>strtotime( $time1->startOfMonth()->toDateTimeString() ),
            'end'  =>strtotime( $time1->endOfMonth()->toDateTimeString() ),
        ];
        while( ($time = strtotime( '+1 months',$time) ) <= strtotime($yctime[1])){
            $time1 = Carbon::parse(date('Y-m',$time));
            $monarr[] = [
                'month'=>date('n',$time).'月',// 取得递增月;
                'start'=>strtotime( $time1->startOfMonth()->toDateTimeString() ),
                'end'  =>strtotime( $time1->endOfMonth()->toDateTimeString() ),
            ];
        }
        unset($time);
        unset($time1);
        return $monarr;
    }

}